package com.hdu.h_health.common;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 通用ViewHolder
 * Created by 612 on 2015/12/11.
 */
public class CommonViewHolder {
    private SparseArray<View> mViews;//存储控件
    private int mPositon;
    private View mConvertView;//convertView

    /**
     * 初始化CommonViewHolder调用
     */
    public CommonViewHolder(Context context, int layoutId, int position, ViewGroup parent){
        mPositon=position;
        //TODO mViews=new SparseArray<View>(layoutId)在真机会OOM
        mViews=new SparseArray<View>();
        mConvertView= LayoutInflater.from(context).inflate(layoutId,parent,false);
        mConvertView.setTag(this);
    }

    /**
     * 入口方法，判定ConvertView是否为空
     */
    public static CommonViewHolder get(Context context, View convertView,
                                 ViewGroup parent, int layoutId, int position) {
        if (convertView==null){
            return new CommonViewHolder(context,layoutId,position,parent);
        }else {
            CommonViewHolder holder= (CommonViewHolder) convertView.getTag();
            holder.mPositon=position;
            return holder;
        }
    }
    /**
     * 通过viewId获取控件
     */
    public <T extends View> T getView(int viewId){
        View view=mViews.get(viewId);
        //判断是否存储过控件的view
        if (view==null){
            view=mConvertView.findViewById(viewId);
            mViews.put(viewId,view);
        }
        return (T)view;
    }

    /**
     * 供给外部访问convertView
     */
    public View getConvertView() {
        return mConvertView;
    }

}
